layui.use(['form','layer'],function(){
	var $ = layui.jquery,
			layer = parent.layer === undefined ? layui.layer : top.layer,
			form = layui.form;
	
	// 添加验证规则
    form.verify({
        userBirthday : function(value){
            if(!/^(\d{4})[\u4e00-\u9fa5]|[-\/](\d{1}|0\d{1}|1[0-2])([\u4e00-\u9fa5]|[-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/.test(value)){
                return "出生日期格式不正确！";
            }
        }
    })
	
    form.on("submit(addUser)",function(data){
        // 弹出loading
        var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        let _id = $(".id").val()
        let _message = "用户添加成功";
        // 获取提交数据
        let _formDate = getDataByQsName(data);
        if(_id == null || _id == ""){
        	console.log(_formDate);
        	// 实际使用时的提交信息
            $.post("../../users/", JSON.parse(_formDate) ,function(res){
           
            })
        }else{
        	// 实际使用时的提交信息
            $.ajax({
                url : "../../users/",
                data : JSON.parse(_formDate),
                type : "PUT"
            })

            _message = "用户修改成功";
        }
        setTimeout(function(){
            layer.close(index);
            layer.msg(_message);
            layer.closeAll("iframe");
            // 刷新父页面
            parent.location.reload();
        },500);
        return false;
    })
	
    /*根据form表单中的自定义属性qs-name获取需要提交数据的字符串*/
    function getDataByQsName(data){
    	let dataStr = "";
    	let _form = data.form;
    	for(let i=0;i<_form.length; i++){
    		let ele = _form[i];
    		let qsName = ele.attributes["qs-name"].value;
    		let val = ele.value;
    		if(val != undefined && val != ""){
    			dataStr += ("\""+qsName + "\":\"" + val + "\",");
    		}
    	}
    	
    	return "{"+cutLastOne(dataStr)+"}";
    }
    
    /* 消除字符串最后一位 */
    function cutLastOne(str){
    	if(str != null && (typeof(str) == "string" && str.length > 1)){
    		return str.substring(0, str.length-1);
    	}
    	return str;
    }
})